#ifdef _WIN32
#include <Windows.h>
#endif
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>

#include "demo.h"


static void sShowError(char *title, char *msg, va_list ap)
{
#ifdef WIN32
    const int BUFLEN = 2048;
    char s[BUFLEN] = { 0 };
    vsnprintf_s(s, BUFLEN, _TRUNCATE, msg, ap);
    MessageBoxA(0, s, title, MB_OK | MB_APPLMODAL | MB_ICONEXCLAMATION);
#else
    fflush(stderr);
    fflush(stdout);
    fprintf(stderr, "\n%s: ", title);
    vfprintf(stderr, msg, ap);
    fprintf(stderr, "\n");
    fflush(stderr);
#endif
}

void gErrorMessage(char *title, char *msg, ...)
{
    va_list ap;
    va_start(ap, msg);
    sShowError(title, msg, ap);
}


#ifdef _WIN32
int CALLBACK WinMain(__in HINSTANCE hInstance,
                     __in HINSTANCE hPrevInstance,
                     __in LPSTR lpCmdLine,
                     __in int nCmdShow)
{
    timeBeginPeriod(1);
    bool success = demo_main(lpCmdLine);
    //if (!success)
    //    MessageBox(NULL, "Error while initializing demo", "Error", MB_OK | MB_ICONERROR);
    timeEndPeriod(1);
    return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
#else
int main(int argc, char *argv[])
{
    bool success = demo_main(argc > 1 ? argv[1] : ""); // Note: passes only 1st arg
    //if (!success)
    //    fprintf(stderr, "Error while initializing demo\n");
    return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
#endif
